import pymysql
import todo
from Rodo.todos.todo import Todo

class Todomysql():
    def get_connec(self):
        return pymysql.Connection(host='192.168.60.130',database='demo',user='root',password='root@123ABC',autocommit= True)

    def set_tabletodo(self):
        with self.get_connec()as conn:
            cursec=conn.cursor()
            cursec.execute('''
            CREATE  table IF NOT EXISTS todos(
            todo_id int NOT NULL auto_increment,
            title VARCHAR(127) NOT NULL DEFAULT '',
            completed INT NOT NULL DEFAULT 0,
            PRIMARY KEY (todo_id)
            ) 
            ''')

    def create(self, title: str):
        with self.get_connec() as conn:
            cursor=conn.cursor()
            cursor.execute('INSERT INTO todos(title) VALUES(%s)',(title,))
            cursor.execute('SELECT LAST_INSERT_ID()')
            (todo_id,)=cursor.fetchone()
            return Todo(title,id=todo_id)

    def create_1(self):
        with self.get_connec() as conn:
             cursor=conn.cursor()
             cursor.execute('SELECT * FROM todos;')
             data=cursor.fetchall()
             return data
    def get_list(self):
        todolist = []
        data=self.create_1()
        for i in data:
            todolist.append(Todo(i[1],id=i[0],completed=True if i[2]==1 else False))
        return todolist
    def mark_completed(self, todo_id):
        with self.get_connec() as conn:
            cursor=conn.cursor()
            todo_id=int(todo_id)
            cursor.execute('DELETE FROM todos WHERE todo_id=(%s)',(todo_id,))
            return '操作成功'

